

from rest_framework.views import APIView
from rest_framework.response import Response
from users.models import User

# timezone是django封装的关于时间处理模块
from django.utils import timezone

from rest_framework.permissions import IsAdminUser

# 用户总数统计
class UserTotalCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 1、查询用户数量
        count = User.objects.count()
        # 2、构造响应返回
        cur_time = timezone.localtime() # 获取'Asia/Shanghai'的本地时间：`2021-6-6 15:45:30 Asia/Shanghai`
        return Response({
            'count': count,
            'date': cur_time.date() # 把datetime对象转化为date对象(只包含年月日)
        })


from  datetime import date
# 日增用户统计
class UserDayCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 1、获取当日的零时刻
        cur_0_time = timezone.localtime().replace(hour=0, minute=0, second=0, microsecond=0)
        # 2、根据当日零时刻过滤当日新增用户数量
        # select * from tb_users where date_joined >= date(2021,6,6,0,0,0);
        count = User.objects.filter(
            date_joined__gte=cur_0_time
        ).count()
        # 3、构建响应
        return Response({
            'count': count,
            'date': cur_0_time.date() # datetime --> date
        })


# 日活跃用户统计
class UserActiveCountView(APIView):

    def get(self, request):
        cur_0_time = timezone.localtime().replace(hour=0, minute=0, second=0, microsecond=0)
        count = User.objects.filter(
            last_login__gte=cur_0_time
        ).count()
        return Response({
            'count': count,
            'date': cur_0_time.date()
        })


from orders.models import OrderInfo
# 日下单用户数量
class UserOrderCountView(APIView):

    def get(self, request):
        # 需求：当日，下的订单，关联的用户数量；
        # (1)、已知条件：当日的0时刻 —— 从表已条件
        # (2)、目标数据：用户数量  —— 主表目标数据
        # 总结：依据"从表已知条件"，查询"主表目标数据"；

        cur_0_time = timezone.localtime().replace(hour=0, minute=0, second=0, microsecond=0)

        # 方案一：从表入手
        # orders = OrderInfo.objects.filter(create_time__gte=cur_0_time)
        # user_set = set()
        # for order in orders:
        #     # order.user是当前订单关联的用户对象
        #     user_set.add(order.user) # 集合add追加数据会自动去重
        # count = len(user_set)
        # return Response({
        #     'count': count,
        #     'date': cur_0_time.date()
        # })

        # 方案二：主表入手
        # 在主表数据查询的过程中，如何使用从表的已知条件 --> 过滤出来的users依然没有去重
        users = User.objects.filter(
            orders__create_time__gte=cur_0_time
        )
        count = len(set(users))

        return Response({
            'count': count,
            'date': cur_0_time.date()
        })

from datetime import timedelta
# 月增用户数量统计
class UserMonthCountView(APIView):

    def get(self, request):
        # 最后一天的0时刻
        end_0_time = timezone.localtime().replace(hour=0, minute=0, second=0)
        # 第一天的0时刻，公式：启始日期 =  当日 - (统计天数 - 1天)
        start_0_time = end_0_time - timedelta(days=29)

        ret_list = []
        for index in range(30):
            # calc_0_time记录某一天的0时刻;next_0_time次日0时刻
            # calc_0_time = start_0_time + 0天   index=0
            # calc_0_time = start_0_time + 1天   index=1
            # calc_0_time = start_0_time + 2天   index=2
            # .....
            # calc_0_time = start_0_time + 29天  index=29
            calc_0_time = start_0_time + timedelta(days=index)
            next_0_time = calc_0_time + timedelta(days=1)

            count = User.objects.filter(
                date_joined__gte=calc_0_time,
                date_joined__lt=next_0_time
            ).count()

            ret_list.append({
                'count': count,
                'date': calc_0_time.date()
            })

        return Response(ret_list)


# from datetime import timedelta
# # 月增用户数量统计
# class UserMonthCountView(APIView):
#
#     def get(self, request):
#         # 统计当月用户数量
#         end_0_time = timezone.localtime().replace(hour=0, minute=0, second=0)
#         # 当月的1日的0时刻
#         start_0_time = end_0_time.replace(day=1)
#
#         # 遍历的天数
#         d_obj = end_0_time - start_0_time # 时间点 - 时间点 = 时间段(timedelta)
#         days = d_obj.days + 1 # 总天数(包含启始那一天)
#
#         ret_list = []
#         for index in range(days):
#             calc_0_time = start_0_time + timedelta(days=index)
#             next_0_time = calc_0_time + timedelta(days=1)
#             count = User.objects.filter(
#                 date_joined__gte=calc_0_time,
#                 date_joined__lt=next_0_time
#             ).count()
#             ret_list.append({
#                 'count': count,
#                 'date': calc_0_time.date()
#             })
#
#         return Response(ret_list)



from rest_framework.generics import ListAPIView
from meiduo_admin.serializers.home_serializers import *
# 商品访问量
class GoodsDayView(ListAPIView):
    queryset = GoodsVisitCount.objects.all()
    serializer_class = GoodsVisitCountSerializer

    def get_queryset(self):
        # 目的：该函数控制了后续序列化操作的目标查询集数据，
        # 重写该函数，可以实现自定义的过滤，分页和排序动作
        # TODO：过滤出当日的分类商品访问量数据
        return self.queryset.filter(
            create_time__gte=timezone.localtime().replace(hour=0,minute=0,second=0)
        )



















